package com.springboot.springbootnetty.nettyservice;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

@Component
public class NettyService {
    public void NettyServer(InetSocketAddress inetSocketAddress) {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        EventLoopGroup workEventExecutors = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(eventExecutors, workEventExecutors)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(
                            new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel socketChannel) throws Exception {
                                    ChannelPipeline ch = socketChannel.pipeline();
                                    ch.addLast(new IdleStateHandler(7000,7000,10, TimeUnit.SECONDS));
                                    ch.addLast(new MyNettyServerHandler());

                                }
                            }
                    );

            // 启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(inetSocketAddress).sync();

            // 监听服务器是否启动成功  类似去去商店点菜，菜点好了，监听这个点菜事件的状态
            channelFuture.addListener(
                    new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) throws Exception {
                            if (channelFuture.isSuccess()) {
                                System.out.println("服务器启动成功");
                            } else {
                                System.out.println("服务器启动失败");
                            }

                        }
                    }
            );
            // 等待服务器关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("服务器启动失败" + e.getMessage());
            throw new RuntimeException(e);
        } finally {
            // 关闭通道
            eventExecutors.shutdownGracefully();
            workEventExecutors.shutdownGracefully();
        }
    }

}
